package com.dao.impl;

import com.dao.BookDao;
import com.entry.Book;
import com.util.DBHelper;


import java.util.ArrayList;


public class BookDaoImpl implements BookDao {

    DBHelper db = new DBHelper();

    @Override
    public ArrayList<Book> selectAll() {
        String sql = "select * from book";
        return db.query(sql,Book.class);
    }

    @Override
    public ArrayList<Book> selectQuery(Book book) {
        StringBuilder sql =new StringBuilder("select * from book where 1=1 ");
        if(book.getBookName()!=null){
            sql.append( "and BOOKNAME like ?");
            return db.query(sql.toString(),Book.class,"%"+book.getBookName()+"%");
        }else if(book.getBookAuthor()!=null){
            sql.append( "and BOOKAUTHOR like ?");
            return db.query(sql.toString(),Book.class,"%"+book.getBookAuthor()+"%");
        }else if(book.getBookPublish()!=null){
            sql.append( "and BOOKPUBLISH like ?");
            return db.query(sql.toString(),Book.class,"%"+book.getBookPublish()+"%");
        }else{
            return db.query(sql.toString(),Book.class);
        }
    }

    @Override
    public boolean insertBook(Book book) {
        String sql="insert into book (BOOKNAME,BOOKAUTHOR,BOOKPUBLISH,BOOKPAGE,BOOKPRICE,CREATEDATE) " +
                "values(?,?,?,?,?,current_date())";
       int i= db.updateTable(sql,book.getBookName(),book.getBookAuthor(),book.getBookPublish(),book.getBookPage(),book.getBookPrice());
       return i==1?true:false;
    }

    @Override
    public boolean deleteBook(int bid) {

        String sql="delete from book where BOOKID=?";

        return db.updateTable(sql,bid)>0?true:false;

    }

    @Override
    public Book selectById(int bid) {
        String sql="select * from book where  BOOKID=? ";
        return (Book)(db.query(sql,Book.class,bid).get(0));
    }

    @Override
    public boolean updateBook(Book book) {
        String sql="update book set BOOKNAME=?,BOOKAUTHOR=?,BOOKPUBLISH=?,BOOKPAGE=?,BOOKPRICE=?,CREATEDATE=?  where BOOKID=?";
        Object[] objs={book.getBookName(),book.getBookAuthor(),book.getBookPublish(),book.getBookPage(),book.getBookPrice(),book.getCreateDate(),book.getBookId()};
        return db.updateTable(sql,objs)>0?true:false;
    }
}
